package com.dataStructure.Stack.MyStack2;

import java.util.Stack;

/**
 * @author xiaboaidsl@163.com
 * 
 * 利用泛型实现stack，基于数组实现，默认初始容量为10,可动态扩展, 每次容量扩展为原来的一倍
 *
 */
public class ArrayStack<E> implements MyStack2<E>{ 
	int capacity; //最大的容量
	int top;
	E[] data;
	
	public ArrayStack() {
		super();
		capacity = 10;// 初始化容量为10
		top = -1;
		data = (E[]) new Object[capacity];
	}
	
	@Override
	public void clear() {
		// TODO Auto-generated method stub
		if (top != -1) {
			for (int i = top; i > -1; i--) {
				data[i] = null; // 
			}
			top = -1;
		}
		
	}
	@Override
	public boolean isEmpty() {
		// TODO Auto-generated method stub
		return top == -1 ? true:false;
	}
	
	/**
	 * 获取stack最顶端数据
	 * @return
	 */
	@Override
	public E peek() {
		// TODO Auto-generated method stub
		if (top == -1) {
			return null;
		}
		return (E) data[top];
	}
	
	/**
	 * 弹出并删除
	 * @return
	 */
	@Override
	public E pop() {
		// TODO Auto-generated method stub
		if (top == -1) {
			return null;
		}
		Object object = data[top];
		data[top] = null;
		top--;
		return (E) object;
	}
	
	
	/**
	 * 向stack中增加一个元素
	 * @param elment
	 */
	@Override
	public void push(E elment) {
		// 容量达到上限，需要扩容
		if (top >= capacity-1) {
			System.out.println("full stack!!");
			return;
		}
		data[++top] = elment;
	}
	
	
	/**
	 * 每当向数组中添加元素时，都要去检查添加后元素的个数是否会超出当前数组的长度，如果超出，数组将会进行扩容，以满足添加数据的需求
	 */
//	public void ensureCapacity(int newCapacity) {
//		System.out.println(data.length);
//		data = Arrays.copyOf(data, newCapacity);
//		System.out.println(data.length);
//		System.out.println("Capacity expand to "+newCapacity);
//	}
	
	
	@Override
	public int size() {
		// TODO Auto-generated method stub
		return top+1;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayStack<Integer> stack_int = new ArrayStack<Integer>();
		for (int i = 0; i < 15; i++) {
			stack_int.push(i);
		}
		System.out.println("stack size: "+stack_int.size());
		int stack_size = stack_int.size();
		//stack pop时stack size会不断变小
		for (int i = 0; i < stack_size; i++) {
			System.out.println(stack_int.pop());
		}
		System.out.println("stack size: "+stack_int.size());
		
		
		
		ArrayStack<String> stack_str = new ArrayStack<String>();
		for (int i = 0; i < 8; i++) {
			stack_str.push("test"+i);
		}
		System.out.println(stack_str.size());
		stack_size = stack_str.size();
		for (int i = 0; i < stack_size; i++) {
			System.out.println(stack_str.pop());
		}
		System.out.println(stack_str.size());
		
		
	}
	

}
